import React, {Component} from 'react';
import {Relax} from 'iflux2';
import {Map, List} from 'immutable';

import {Row, Col, Checkbox, Select, InputNumber, message, Spin} from 'antd';
const Option = Select.Option;

import noop from 'util/noop';
import {routerShape} from 'constant/PropTypes';
import {createLocationDescriptor} from 'util/history';

@Relax
export default class OrderInfo extends Component {
    static defaultProps = {
        marketingOrder: Map(),
        addressList: List(),
        jifen: Map(),
        receiptId: '',
        payTypeId: '',
        shipFee: 0,
        couponId: undefined,
        integral: undefined,
        invoice: Map(),

        calculateCouponTotal: noop,
        chooseCoupon: noop,
        changeUsed: noop,
        calculateIntegralTotal: noop,
        calculateValidIntegralTotal: noop,
        changeIntegral: noop,
        calculatePayTotal: noop,
        createTrade: noop
    }

    //路由跳转
    static contextTypes = {
        router: routerShape
    }


    constructor(props) {
        super(props);

        this.state = {
            userCoupon: false,
            userIntegral: false,
            createTradeLoading: false,
            errorMsg: ''
        }
    }


    render() {
        const {marketingOrder, jifen, couponId, integral,
            calculateCouponTotal, calculateIntegralTotal, calculateValidIntegralTotal, changeIntegral,
            calculatePayTotal, createTrade} = this.props;
        const {userCoupon, userIntegral, errorMsg, createTradeLoading} = this.state;

        return (
            <Spin spinning={createTradeLoading}
                  tip="订单创建中..."
                  delay="200">
                <Row className="order-pay-detail">
                    <Col span={10}>
                        <div className="t-grayer">
                            <p>返积分{(jifen.get('totalGiftIntegralPoint') || 0) + (marketingOrder.get('integral') || 0)}点</p>
                        </div>
                    </Col>
                    <Col span={12} offset={2}>
                        {
                            jifen.get('open')
                                ?
                                <Row className="pushb">
                                    <Col span={18}>
                                        <Checkbox checked={userIntegral}
                                                  onChange={()=>this.changeUsed('userIntegral')}>使用积分：</Checkbox>
                                        {
                                            userIntegral
                                                ? <div className="inline-blk">
                                                    <InputNumber placeholder="输入积分"
                                                                 className="w220"
                                                                 value={integral}
                                                                 onChange={(integral)=>changeIntegral(integral)}
                                                                 min={0}
                                                                 max={Number(calculateValidIntegralTotal().toFixed(2))}/>
                                                    <span className="pushl">可用积分：<span className="t-red">{calculateValidIntegralTotal().toFixed(2)}</span></span>
                                                </div>
                                                : null
                                        }
                                    </Col>
                                    <Col span={6}>
                                        <div className="t-right">-&yen;{calculateIntegralTotal().toFixed(2)}</div>
                                    </Col>
                                </Row>
                                :
                                null
                        }
                        <Row className="pushb">
                            <Col span={18}>
                                <Checkbox checked={userCoupon}
                                          onChange={()=>this.changeUsed('userCoupon')}>用优惠券：</Checkbox>
                                {
                                    userCoupon
                                        ? <div className="inline-blk w220">
                                            <Select placeholder="选择优惠券"
                                                    notFoundContent='暂无优惠券可用'
                                                    value={couponId}
                                                    onSelect={(value)=>this.chooseCoupon(value)}>
                                                {
                                                    (marketingOrder.get('availableUserCoupons') || List()).map((coupon, index)=>{
                                                        return <Option key={index}
                                                                       value={coupon.get('couponId')}>{`满${coupon.get('limitFee')}元减${coupon.get('value')}元优惠券`}</Option>
                                                    })
                                                }
                                            </Select>
                                        </div>
                                        : null
                                }
                            </Col>
                            <Col span={6}><div className="t-right">-&yen;{calculateCouponTotal().toFixed(2)}</div></Col>
                        </Row>
                        <div className="order-payInfo">
                            <div className="payInfo-wrapper">
                                <div className="payInfo-shadow">
                                    <div className="order-realPay">
                                        <div>
                                            <span className="realPay-title">应付款：</span>
                                            <span className="realPay-price t-price">&yen;{calculatePayTotal().toFixed(2)}</span>
                                        </div>
                                    </div>
                                    {this.renderReceipt()}
                                </div>
                            </div>
                        </div>
                        <div className="order-submitOrder">
                            <a className="order-submitOrderBtn" href="javascript:void(0);" onClick={()=>this.createTrade()}>提交订单</a>
                            <span className="pull-right">
                        <span className="msg-error">{errorMsg}</span>
                        </span>
                        </div>
                    </Col>
                </Row>
            </Spin>
        )
    }


    renderReceipt() {
        const {addressList, receiptId} = this.props;

        const receipt = addressList.find(address=>address.get('receiptId') == receiptId);

        if (!!receipt) {
            const {province, city, area, detailAddress, receiptUserName, phone} = this.spiltArea(receipt.toJS());

            return (
                <div className="order-confirmAddr">
                    <div className="confirmAddr-addr"><span className="confirmAddr-title">寄送至：</span>
                        <span className="confirmAddr-addr-bd"><span className="prov">{province}</span><span className="city">{city}</span><span className="dist">{area}</span><span className="street">{detailAddress}</span></span>
                    </div>
                    <div className="confirmAddr-addr-user"><span className="confirmAddr-title">收货人：</span>
                        <span className="confirmAddr-addr-bd"><span>{receiptUserName}</span><span>{phone}</span></span>
                    </div>
                </div>
            )
        }

        return null;
    }


    spiltArea(receipt) {
        const {province, city, area, detailAddress, mobilePhone, receiptUserName, ...rest} = receipt;

        return {
            province: province.split('-')[1],
            city: (city || '-').split('-')[1],
            area: (area || '-').split('-')[1],
            detailAddress,
            receiptUserName,
            phone: mobilePhone || rest.fixPhone
        }
    }


    changeUsed(type) {
        this.setState({
            [type]: !this.state[type]
        });

        this.props.changeUsed(type);
    }

    chooseCoupon(couponId) {
        this.props.chooseCoupon(couponId);
    }

    createTrade(params) {
        const {payTypeId} = this.props;
        const _this = this;
        this.setState({
            createTradeLoading: true
        })
        this.props.createTrade(params).then(()=>{
            message.success(`订单创建成功,即将跳转到${payTypeId === "GRP" ? '销售单' : '未支付订单'}列表页面`);
            setTimeout(()=>{
                _this.context.router.replace(createLocationDescriptor(`/order/list/${payTypeId === "GRP" ? 'sales' : 'unpay'}`));
            }, 1000);
        }).catch(msg=>{
            _this.setState({
                createTradeLoading: false,
                errorMsg: msg
            })
        })
    }
}